/* Copyright (c) 2020-2022 Qualcomm Technologies International, Ltd. */
/* %%version */


#include "gatt_mcs_client_common_util.h"
#include "gatt_mcs_client_debug.h"

#ifndef SYNERGY_MCP_ENABLE
static void mcsClientSendTerminateCfm(GMCSC * mcsClient, GattMcsClientStatus status)
{
    GattMcsClientTerminateCfm *message = CsrPmemAlloc(sizeof(*message));

    message->status = status;
    message->srvcHndl = mcsClient->srvcElem->service_handle;

    memcpy(&(message->deviceData), &(mcsClient->handles), sizeof(GattMcsClientDeviceData));

    McsMessageSend(mcsClient->appTask, GATT_MCS_CLIENT_TERMINATE_CFM, message);
}
#endif

/****************************************************************************/
void GattMcsClientTerminateReq(ServiceHandle clntHndl)
{
    GMCSC *mcsClient = ServiceHandleGetInstanceData(clntHndl);

    if (mcsClient)
    {
        bool res = FALSE;
        AppTask appTask = mcsClient->appTask;
        GattMcsClientTerminateCfm *message = CsrPmemAlloc(sizeof(*message));
        GattMcsClient *mcsClientMain = mcsClientGetMainInstance();

#ifndef SYNERGY_MCP_ENABLE
        /* Unregister with the GATT Manager and verify the result */
        if (GattManagerUnregisterClient(&mcsClient->libTask) == gatt_manager_status_success)
        {
            /* Clear pending messages */
            MessageFlushTask((AppTask)&mcsClient->libTask);
#else
            CsrBtGattUnregisterReqSend(mcsClient->srvcElem->gattId);
#endif

            memcpy(&(message->deviceData), &(mcsClient->handles), sizeof(GattMcsClientDeviceData));

            message->srvcHndl = mcsClient->srvcElem->service_handle;

            /* Remove the service element from main list */
            if (mcsClientMain)
                MCS_REMOVE_SERVICE_HANDLE(mcsClientMain->serviceHandleList, mcsClient->srvcElem);

            /* Free the service instance memory */
            res = ServiceHandleFreeInstanceData(clntHndl);

            if (res)
            {
                message->status = GATT_MCS_CLIENT_STATUS_SUCCESS;
            }
            else
            {
                message->status = GATT_MCS_CLIENT_STATUS_FAILED;
            }
#ifndef SYNERGY_MCP_ENABLE
        }
        else
        {
            mcsClientSendTerminateCfm(mcsClient, GATT_MCS_CLIENT_STATUS_FAILED);
        }
#endif
            McsMessageSend(appTask, GATT_MCS_CLIENT_TERMINATE_CFM, message);
        }
    else
    {
        GATT_MCS_CLIENT_ERROR("Invalid MCS memory instance!\n");
    }
}
